import get from "lodash/get";
import eventBus from "../../../framework/common/eventBus";
import message from "../../../framework/common/utils/message";
import request from "../../../framework/common/utils/request";

import getInitiateFormData from "../../../framework/common/utils/getInitiateFormData";
import { initStepData } from "./../stepUtility";/*审批步骤数据清洗*/

//选择步骤分支
/**
 * 
 * @param {*} stepInfo 
 * branchStepIndex 选中的分支步骤索引
 * stepIndex 当前步骤的索引
 */
function chooseStep ({
    stepInfo,
    approveSteps,
    actual_steps,
    params,
    tplData,
    approveType,
    setLoading,
    temporaryStepCache,
    validateResultRef,
    approveStepsRef,
    actual_stepsRef,
    selectStepId
}) {
    let stepIndex = stepInfo.stepIndex;//步骤索引
    let branchStepIndex = stepInfo.branchStepIndex;//选中的分支步骤索引
    var path = stepIndex + ".branch." + branchStepIndex;
    var branchStep = get(approveSteps, path);
    var branch = approveSteps[stepIndex].branch;
    branch.forEach(function(step, i) {
        step.nodes = null;
        step.needChoose = null;
        step.tag = null;
        step.chooseed = null;
    });
    branchStep.chooseed = true;
    var c_Step = approveSteps[stepIndex - 1];//当前分支步骤的上一个步骤
    var ind = 0;
    actual_steps.map(function(item, i) {//实际步骤
        if (item.id == c_Step.id) {//当前分支步骤的上一个步骤
            ind = i;
            item.toStepIds = [branchStep.id];//给一个toStepIds = 当前选中的分支步骤的id
        }
    });
    approveSteps.map(function(item, i) {//所有步骤
        if (item.id == c_Step.id) {//当前分支步骤的上一个步骤
            item.toStepIds = [branchStep.id];//给一个toStepIds = 当前选中的分支步骤的id
        }
    });

    let postObj = getInitiateFormData({
        params: params, 
        tplData: tplData, 
        approveType: approveType || "",//审批类型
        type: 'getBranchStep'
    });

    postObj['actual_steps'] = actual_steps.slice(0, ind + 1);
    postObj['choose_step_id'] = branchStep.id;
    eventBus.publish("setBranchLoading.update", true);//加载状态
    setLoading?.(true);//父组件设置loading
    return request({
        url: "/flowinstance/process/choose-branch-step",
        method: "POST",
        data: postObj,
    }).then(
        function(resObj){
            eventBus.publish("setBranchLoading.update", false);//加载状态
            setLoading?.(false);//父组件设置loading
            if (resObj.code == 1 && resObj.data) {
                
                var cacheBranch = temporaryStepCache[branchStep.id];

                //给选中的分支步骤信息进行赋值操作
                var currChoosedStep = resObj.data.actual_steps[0];
                branchStep.nodes = currChoosedStep.nodes;
                branchStep.needChoose = currChoosedStep.needChoose;
                branchStep.tag = currChoosedStep.tag;
                branchStep.chooseed = true;

                var nextStep = cacheBranch && cacheBranch.length ? cacheBranch : resObj.data.actual_steps.slice(0);//选中分支后的剩余步骤
                nextStep = initStepData({
                    steps: nextStep,
                    multiUserSelect: tplData.ProcessInfo.MultiUserSelect
                });

                //更新所有步骤
                var newApproveSteps = approveSteps.slice(0, stepIndex - 0 + 1);
                newApproveSteps = newApproveSteps.concat(nextStep);

                //不知道这里逻辑是干什么的
                if (
                    currChoosedStep.needChoose && currChoosedStep.nodes.length == 0 
                    && (
                        currChoosedStep.stepAttrs 
                        && currChoosedStep.stepAttrs.no_auditor_rules 
                        && currChoosedStep.stepAttrs.no_auditor_rules.indexOf('SkipStep') == -1 
                        && !currChoosedStep.stepAttrs.adjust_auditor || currChoosedStep.step_type == 2
                        )
                    ) 
                {
                    newApproveSteps[stepIndex].checkTip = true;
                }

                //返回的步骤依然包含分支信息，追加到末尾继续选
                if (resObj.data.branch && resObj.data.branch.length) {
                    newApproveSteps.push({
                        branch: resObj.data.branch
                    });
                }

                var newActual_steps = [];//对应原属性 explicitStepsPath_module.actual_steps
                newApproveSteps.map(function(item, i) {
                    if(item.id && !item.branch){
                        newActual_steps.push(item);//不知道这里逻辑干什么的
                    }
                });

                let newValidateResult = null;
                if (resObj.data.validateResult) {
                    if (resObj.data.validateResult.errorCode == 30015) {
                        newValidateResult = resObj.data.validateResult;
                    }
                    if (resObj.data.validateResult.errorCode == 30012 || resObj.data.validateResult.errorCode == 30011) {
                        newValidateResult = "";
                    }
                }

                updataSteps({
                    approveSteps: newApproveSteps,//更新流程图 _this.refreshSteps();
                    actual_steps: newActual_steps,
                    approveStepsRef: approveStepsRef,
                    actual_stepsRef: actual_stepsRef,
                    selectStepId: selectStepId
                });//更新步骤

                validateResultRef.current = newValidateResult;//更新错误信息
                eventBus.publish("setStepHasNoError.update", newValidateResult);//父组件更新validateInfo，用于控制请求失败后，弹出框按钮显示为 “我知道了”

                eventBus.publish("updateEditStep.update");
            }
        },
        function(){
            eventBus.publish("setBranchLoading.update", false);//加载状态
            setLoading?.(false);//父组件设置loading
            message.info({
                content: "获取分支信息失败",
            });
        }
    )
}

function deleteTemporaryStep({
    dataPath,
    approveSteps,
    actual_steps,
    temporaryStepCache,
    approveStepsRef,
    actual_stepsRef,
    selectStepId
}){
    var index = dataPath;
    var p_index = index;
    var step = approveSteps[index-0],previousStep = approveSteps[index-0-1];
    var p__prev_step = actual_steps.find(function(s) {
        return s.id == previousStep.id;
    });
    actual_steps.find(function(s,i) {
        if(s.id == step.id){
            p_index = i;
        }
        return s.id == step.id;
    })
    var toStepIds = step.toStepIds;
    previousStep.toStepIds = toStepIds;
    p__prev_step.toStepIds = toStepIds;

    if(previousStep.oldToStepIds+'' == toStepIds+''){
        previousStep.oldToStepIds = [];
        p__prev_step.oldToStepIds = [];
    }

    if(step.temporaryStep && step.temporaryStepToId){
        previousStep.temporaryStepToId = step.temporaryStepToId;
        p__prev_step.temporaryStepToId = step.temporaryStepToId;
    }

    //更新步骤的默认分支配置
    var default_transition_to_activity = step.default_transition_to_activity;
    // 只有在默认分支上新增临时步骤需要处理默认分支继承关系
    if(default_transition_to_activity && toStepIds.length == 1 && toStepIds[0] == default_transition_to_activity){
        previousStep.default_transition_to_activity = default_transition_to_activity;
        p__prev_step.default_transition_to_activity = default_transition_to_activity;
        step.default_transition_to_activity = '';
    }

    approveSteps.splice(index-0,1);
    actual_steps.splice(p_index,1);

    var leftInd = index-0-1,rightInd = index-0,leftGo = true,rightGo = true;

    while (leftGo || rightGo) {
        if(leftInd <= 0){
            leftGo = false;
        }else{
            if(approveSteps[leftInd].branch){
                leftGo = false;
            }else{
                leftInd--;
            }
        }

        if(rightInd >= approveSteps.length){
            rightGo = false;
        }else{
            if(approveSteps[rightInd].branch){
                rightGo = false;
            }else{
                rightInd++;
            }
        }

    }

    // 缓存新增的步骤
    if(rightInd != 0){
        var branchCacheStep = approveSteps.slice(leftInd+1,rightInd);
        if(branchCacheStep && branchCacheStep.length){
            temporaryStepCache[branchCacheStep[0].id] = branchCacheStep;
        }
    }
    
    updataSteps({
        approveSteps: approveSteps,//更新流程图 _this.refreshSteps();
        actual_steps: actual_steps,
        approveStepsRef: approveStepsRef,
        actual_stepsRef: actual_stepsRef,
        selectStepId: selectStepId
    });//更新步骤
    eventBus.publish("updateEditStep.update");//更新步骤信息_this.refreshSteps();
}

//checkbox change事件-并行/串行 多人时选择责任人
function onNodesChange({
    e, 
    nodes, 
    step,
    actual_steps
}){
    nodes.map(function(nodeItem){
        if(e.indexOf(nodeItem.auditor_id) > -1){
            nodeItem.Checked = true;
        }else{
            nodeItem.Checked = false;
        }
    });
    let p_step = actual_steps.find(function(s) {
        return s.id == step.id;
    });
    p_step.nodes = JSON.parse(JSON.stringify(step.nodes));//同步更新 actual_steps
    eventBus.publish("updateEditStep.update");
}

//添加临时步骤
function addTemporaryStep({
    dataPath,
    approveSteps,
    actual_steps,
    temporaryStepCache,
    approveStepsRef,
    selectStepId,
    actual_stepsRef
}){

    //删除临时步骤
    var index = dataPath;
    var p_index = dataPath;
    var id = 'new_' + (+new Date()) + '_' + (((1 + Math.random())*0x10000)|0).toString(16).substring(1);
    var step = approveSteps[index-0];
    //steps里存的是渲染确认路径交互的步骤数据，actual_steps存的是提交到后台的数据，两者数据格式可能不一样
    var p_step = {};
    actual_steps.forEach(function(s, i) {
        if(s.id == step.id){
            p_index = i;
        }
        if(s.id == step.id){
            p_step = s;
        }
    })
    var toStepIds = p_step.toStepIds;
    step.toStepIds = [id];
    p_step.toStepIds = [id];
    step.temporaryStepToId = step.toStepIds;
    p_step.temporaryStepToId = step.toStepIds;

    var temporaryStepToId = toStepIds;
    if(approveSteps[index-0+1] && approveSteps[index-0+1].branch){
        temporaryStepToId = [];
        approveSteps[index-0+1].branch.forEach(function(item){
            temporaryStepToId.push(item.id);
        });
    }

    if(!step.oldToStepIds || step.oldToStepIds.length == 0){
        step.oldToStepIds = temporaryStepToId;
        p_step.oldToStepIds = temporaryStepToId;
    }

    var _step = {
        stepAttrs:{multi_type:'Multi',handle_mode:'Serial'},
        name:'',
        nodes:[],
        id:id,
        temporaryStep:true,
        temporaryStepToId: temporaryStepToId,
        toStepIds:toStepIds
    };

    //更新步骤的默认分支配置
    var default_transition_to_activity = step.default_transition_to_activity;
    // 只有在默认分支上新增临时步骤需要处理默认分支继承关系
    if(default_transition_to_activity && toStepIds.length == 1 && toStepIds[0] == default_transition_to_activity){
        _step.default_transition_to_activity = default_transition_to_activity;
        step.default_transition_to_activity = '';
        p_step.default_transition_to_activity = '';
    }

    approveSteps.splice(index-0+1,0,_step);
    actual_steps.splice(p_index+1,0,_step);

    var leftInd = index-0,
        rightInd = index-0 + 1,
        leftGo = true,
        rightGo = true;

    while (leftGo || rightGo) {
        if(leftInd <= 0){
            leftGo = false;
        }else{
            if(approveSteps[leftInd].branch){
                leftGo = false;
            }else{
                leftInd--;
            }
        }

        if(rightInd >= approveSteps.length){
            rightGo = false;
        }else{
            if(approveSteps[rightInd].branch){
                rightGo = false;
            }else{
                rightInd++;
            }
        }
    }

    // 缓存新增的步骤
    if(rightInd != 0){
        var branchCacheStep = approveSteps.slice(leftInd+1,rightInd);
        if(branchCacheStep && branchCacheStep.length){
            temporaryStepCache[branchCacheStep[0].id] = branchCacheStep;
        }
    }

    updataSteps({
        approveSteps: approveSteps,//更新流程图 _this.refreshSteps();
        actual_steps: actual_steps,
        approveStepsRef: approveStepsRef,
        selectStepId: selectStepId,
        actual_stepsRef: actual_stepsRef
    });//更新步骤
    eventBus.publish("updateEditStep.update");
}

//更新步骤信息
function updataSteps({
    approveSteps,
    actual_steps,
    approveStepsRef,
    actual_stepsRef,
    selectStepId
}){
    approveStepsRef.current = approveSteps;
    actual_stepsRef.current = actual_steps;
    eventBus.publish("setReturnSteps.update", actual_steps);
    eventBus.publish("setAllSteps.update", approveSteps);

    //重置流程路径选中的步骤id
    if(selectStepId.current){
        let hasSelectStep = actual_steps.find(function(item){
            return item.id === selectStepId.current;
        });//在最新的步骤内，找是否存在已选择过的步骤id
        if(hasSelectStep){
            //最新步骤内存在已选的步骤id，不做响应
        }else{
            //已有步骤内不存在已选择过的步骤，说明切换分支后，已选过的不做被清掉了
            //1.清空window对象内的缓存，调用流程图更新时，不会做选中操作
            window._selectrdStepId = null;
            //2.清空组件内的选中标记，更新后的流程图不会有选中效果
            selectStepId.current = null;
        }
    }

    //更新iframe依赖的流程信息
    window._stepsPath = actual_steps;
    eventBus.publish("handlestepsPath,update");
}

export{
    chooseStep,
    deleteTemporaryStep,
    onNodesChange,
    addTemporaryStep//添加临时步骤
}